let SWDA_ItemCostMpTp = {};


//=============================================================================
// DataManager
//=============================================================================
// 读取数据库中备注
SWDA_ItemCostMpTp.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function () {
    if (!SWDA_ItemCostMpTp.DataManager_isDatabaseLoaded.call(this)) return false;
    if (!SWDA_ItemCostMpTp._loaded) {
        this.processICMTNotetags($dataItems);
        this.processICMTNotetags($dataWeapons);
        this.processICMTNotetags($dataArmors);


        SWDA_ItemCostMpTp._loaded = true;
    }
    return true;
};

DataManager.processICMTNotetags = function (group) {
    for (var n = 1; n < group.length; n++) {
        var obj = group[n];
        var notedata = obj.note.split(/[\r\n]+/);

        obj.hpCost = [];
        obj.mpCost = [];
        obj.tpCost = [];

        for (var i = 0; i < notedata.length; i++) {
            var line = notedata[i];
            if (line.match(/<HP[ ]COST:[ ](\d+)>/i)) {
                var hpcost = parseInt(RegExp.$1);
                obj.hpCost = hpcost;
            }
            if (line.match(/<MP[ ]COST:[ ](\d+)>/i)) {
                var mpcost = parseInt(RegExp.$1);
                obj.mpCost = mpcost;
            }
            if (line.match(/<TP[ ]COST:[ ](\d+)>/i)) {
                var tpcost = parseInt(RegExp.$1);
                obj.tpCost = tpcost;
            }
        }
    }
};
//=============================================================================
// Game_BattlerBase
//=============================================================================


//=============================================================================
// Game_BattlerBase
//=============================================================================

Game_BattlerBase.prototype.canPayItemCost = function (item) {
    /*
    if(CP.PetManager.isAddPetItem(item)){
        item = $dataArmors[$dataEnemies[item.petAddedInfo.enemyId].catchGainItem[16].itemId];
    }
    */
    return  this._hp >= this.itemHpCost(item) && this._tp >= this.itemTpCost(item) && this._mp >= this.itemMpCost(item);
};

Game_BattlerBase.prototype.itemHpCost = function (item) {
    return item.hpCost;
};

Game_BattlerBase.prototype.itemMpCost = function (item) {
    return item.mpCost;
};

Game_BattlerBase.prototype.itemTpCost = function (item) {
    return item.tpCost;
};

Game_BattlerBase.prototype.payItemCost = function (item) {
    this._hp -= this.itemHpCost(item);
    this._mp -= this.itemMpCost(item);
    this._tp -= this.itemTpCost(item);
};

SWDA_ItemCostMpTp.GameBattlerBase_meetsItemConditions =
    Game_BattlerBase.prototype.meetsItemConditions;
Game_BattlerBase.prototype.meetsItemConditions = function (item) {
    //return SWDA_ItemCostMpTp.GameBattlerBase_meetsItemConditions.call(this,item);
    return this.canPayItemCost(item) && SWDA_ItemCostMpTp.GameBattlerBase_meetsItemConditions.call(this, item);
};


SWDA_ItemCostMpTp.GameBattler_consumeItem =
    Game_Battler.prototype.consumeItem
Game_Battler.prototype.consumeItem = function (item) {
    SWDA_ItemCostMpTp.GameBattler_consumeItem.call(this, item);
    this.payItemCost(item);
};


//=============================================================================
// Game_BattlerBase
//=============================================================================
SWDA_ItemCostMpTp.Window_ItemList_drawItem =
    Window_ItemList.prototype.drawItem;
Window_ItemList.prototype.drawItem = function (index) {
    SWDA_ItemCostMpTp.Window_ItemList_drawItem.call(this, index);
    var item = this._data[index];
    if (item) {
        var rect = this.itemRect(index);

        // 画法宝经验槽
        var iconBoxWidth = Window_Base._iconWidth + 4;
        let itemObject = new Game_Item();
        itemObject.setObject(item);
        if (itemObject.isMagicWeapon()) {
            this.drawItemExp(itemObject, rect.x + iconBoxWidth, rect.y + 2, 150);
        }

        var numberWidth = this.textWidth('000');
        if (DataManager.isIndependent(item)){
            numberWidth = 0;
        }
        //var numberWidth = this.numberWidth();
        
        rect.width -= this.textPadding();
        this.changePaintOpacity(this.isEnabled(item));
        if (this._category == 'equips'){
            this.drawItemUsable(item, rect.x, rect.y, rect.width - numberWidth);
        }else{
            this.drawItemCost(item, rect.x, rect.y, rect.width - numberWidth);
        }
        this.changePaintOpacity(1);
    }
};

Window_ItemList.prototype.drawItemUsable = function (item, wx, wy, width) {
    if (CP.UseEquipManager.isEquipUsable(item)){
        wx -= Window_Base._iconWidth;
        this.setSmallerFont();
        this.contents.fontSize = Yanfly.Param.SCCHpFontSize;
        this.drawText('可用于' + item.itemCategory, wx, wy, width, 'right');
        this.resetFontSettings();
    }
};

Window_ItemList.prototype.drawItemCost = function (item, wx, wy, width) {
    if (CP.UseEquipManager.isEquipUsable(item))
        item = CP.UseEquipManager.getRealUseItem(item);
    var dw = width;
    dw = this.drawHpCost(item, wx, wy, dw);
    dw = this.drawMpCost(item, wx, wy, dw);
    dw = this.drawTpCost(item, wx, wy, dw);
    return dw;
};

Window_ItemList.prototype.drawHpCost = function(item, wx, wy, dw) {
    if (item.hpCost <= 0) return dw;
   
    // 画图标
    if (Yanfly.Icon.Hp > 0) {
      var iw = wx + dw - Window_Base._iconWidth;
      this.drawIcon(Yanfly.Icon.Hp, iw, wy + 2);
      dw -= Window_Base._iconWidth + 2;
    }
    // 画文字
    this.changeTextColor(this.textColor(Yanfly.Param.SCCHpTextColor));
    var fmt = Yanfly.Param.SCCHpFormat;
    var text = fmt.format(Yanfly.Util.toGroup(item.hpCost),
      TextManager.hpA);
    this.contents.fontSize = Yanfly.Param.SCCHpFontSize;
    this.drawText(text, wx, wy, dw, 'right');
    // 返回
    var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding;
    this.resetFontSettings();
    return returnWidth;
};
Window_ItemList.prototype.drawMpCost = function (item, wx, wy, dw) {
    if (item.mpCost <= 0) return dw;
    // 画图标
    if (Yanfly.Icon.Mp > 0) {
        var iw = wx + dw - Window_Base._iconWidth;
        this.drawIcon(Yanfly.Icon.Mp, iw, wy + 2);
        dw -= Window_Base._iconWidth + 2;
    }
    // 画文字
    this.changeTextColor(this.textColor(Yanfly.Param.SCCMpTextColor));
    var fmt = Yanfly.Param.SCCMpFormat;
    var text = fmt.format(Yanfly.Util.toGroup(item.mpCost),
        TextManager.mpA);
    this.contents.fontSize = Yanfly.Param.SCCMpFontSize;
    this.drawText(text, wx, wy, dw, 'right');
    // 返回
    var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding;
    this.resetFontSettings();
    return returnWidth;
};

Window_ItemList.prototype.drawTpCost = function (item, wx, wy, dw) {
    if (item.tpCost <= 0) return dw;
    // 画图标
    if (Yanfly.Icon.Tp > 0) {
        var iw = wx + dw - Window_Base._iconWidth;
        this.drawIcon(Yanfly.Icon.Tp, iw, wy + 2);
        dw -= Window_Base._iconWidth + 2;
    }
    // 画文字
    this.changeTextColor(this.textColor(Yanfly.Param.SCCTpTextColor));
    var fmt = Yanfly.Param.SCCTpFormat;
    var text = fmt.format(Yanfly.Util.toGroup(item.tpCost),
        TextManager.tpA);
    this.contents.fontSize = Yanfly.Param.SCCTpFontSize;
    this.drawText(text, wx, wy, dw, 'right');
    // 返回
    var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding;
    this.resetFontSettings();
    return returnWidth;
};


//=============================================================================
// Game_BattlerBase
//=============================================================================
SWDA_ItemCostMpTp.SceneItem_user = Scene_Item.prototype.user;
Scene_Item.prototype.user = function () {
    var bestActor = SWDA_ItemCostMpTp.SceneItem_user.call(this);

    // 计算user时临时计算目标，把使用者调整为目标
    //（遍历目标，谁最先满足MP/TP消耗条件，则谁为使用者。)
    // 若都不符合，则维持原本的“使用者”
    const item = this.item()
    const isMpTpItem = (item.mpCost > 0 || item.mpCost > 0);
    if (this._actorWindow.index() >= 0 && isMpTpItem) {
        var action = new Game_Action(bestActor);
        action.setItemObject(this.item());
        if (!action.isForFriend()) {
        } else if (action.isForAll()) {
            var targets = $gameParty.members();
            for (var i = 0; i < targets.length; i++) {
                if (targets[i].canPayItemCost(item)) {
                    bestActor = targets[i];
                    return bestActor;
                }
            }
        } else {
            var targets = [$gameParty.members()[this._actorWindow.index()]];
            bestActor = targets[0];
            return bestActor;
        }
    }
    return bestActor;
};
